import axios from 'axios'
import type { Method } from 'axios'
import { showToast } from 'vant'
// import i18n from 'i18next'

const http = axios.create({
  baseURL: (import.meta as any).VITE_APP_BASE_URL,
  timeout: 30000,
  withCredentials: false
})

http.interceptors.request.use(
  config => config,
  error => Promise.reject(error)
)

http.interceptors.response.use(
  res => res.data,
  err => {
    console.log('http error:', err)
    if (!window.navigator.onLine) {
      // showToast .show({
      //   content: i18n.t(),
      // })
      showToast('Please check network connection')
    }

    if (err.response && err.response.status === 401) {
      window.sessionStorage.removeItem('token')
      return Promise.resolve(null)
    }

    return Promise.reject(err)
  }
)

export const instance = ({
  url,
  method,
  params,
  data
}: {
  url: string
  method: Method | string
  params?: Record<string, any>
  data?: Record<string, any>
}) =>
  new Promise<any>((resolve, reject) => {
    const token = window.sessionStorage.getItem('token')
    http({
      url,
      method,
      headers: {
        Authorization: `Bearer ${token ? token : ''}`
      },
      params,
      data
    })
      .then(res => {
        if (typeof res === 'string') {
          res = eval('(' + res + ')')
        }
        const code = (res as any).code
        if (!code) {
          //非系统内API
          resolve(res as any)
        }
        //console.log('http res:', typeof res, code, res)
        if (code !== 0) {
          //showToast((res as any).msg)
          reject(res as any)
        } else {
          resolve(res as any)
        }
      })
      .catch(err => {
        reject(err)
      })
  })
